package top.market.redis;

import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;

public class LyhLuaUtils {

    public static DefaultRedisScript<Integer> applyInt(String luaPath){
        DefaultRedisScript<Integer> redisScript = new DefaultRedisScript<>();
        // redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("luascript/lock-set.lua")));
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource(luaPath)));
        redisScript.setResultType(Integer.class);
        return redisScript;
    }

    public static DefaultRedisScript<Boolean> applyBoolean(String luaPath){
        DefaultRedisScript<Boolean> redisScript = new DefaultRedisScript<>();
        // redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource(luaPath, "utf-8")));
        // EncodedResource
        ClassPathResource classPath = new ClassPathResource(luaPath);
        String encode = "utf-8";
        Charset charset = StandardCharsets.US_ASCII;
//        EncodedResource encodedResource = new EncodedResource(classPath, encode);
//        redisScript.setScriptSource(new ResourceScriptSource(encodedResource));
        // 使用 黑马点评 测试
        redisScript.setLocation(new ClassPathResource(luaPath));
        redisScript.setResultType(Boolean.class);
        return redisScript;
    }

    // String ...args 可变参数
    public static Integer applyInt(StringRedisTemplate stringRedisTemplate, String luaPath, List<String> keys , String ...values){
        DefaultRedisScript<Integer> redisScript = new DefaultRedisScript<>();
        // redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("luascript/lock-set.lua")));
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource(luaPath)));
        redisScript.setResultType(Integer.class);
        return stringRedisTemplate.execute(redisScript, keys, values);
    }

    public static Boolean applyBoolean(StringRedisTemplate stringRedisTemplate, String luaPath, List<String> keys , String ...values){
        DefaultRedisScript<Boolean> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource(luaPath)));
        redisScript.setResultType(Boolean.class);
        return stringRedisTemplate.execute(redisScript, keys, values);
    }

}
